package cn.com.dnt.jmxmonitor.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import cn.com.dnt.jmxmonitor.util.JSONUtil;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

@SuppressWarnings("restriction")
public class JMXHttpServer {
	
	public static final int port = 8888;// 监听的端口号
	
	public static void main(String[] args) throws IOException {
		String envValue = System.getenv("JMX_MONITOR_PORT");
		String sysValue = System.getProperty("jmx.monitor.port");
		// 暴露监听端口
		int monitorPort = port;
		if (sysValue != null) {
			monitorPort = Integer.parseInt(sysValue);
		} else if (envValue != null) {
			monitorPort = Integer.parseInt(envValue);
		}
		InetSocketAddress addr = new InetSocketAddress(monitorPort);  
		//创建一个httpserver实例，0表示开启服务  
		HttpServer server = HttpServer.create(addr, 0);  
		server.createContext("/jmx/weblogic/thread", new WeblobicJmxHandler());  
		server.createContext("/jmx/tomcat/thread", new TomcatJmxHandler());  
		//这里指定了Filter  
		server.setExecutor(Executors.newCachedThreadPool());  
		server.start();  
		System.out.println("server start...");
		System.out.println("server port:" + monitorPort);
	}
	
	private static class TomcatJmxHandler implements HttpHandler {

		@Override
		public void handle(HttpExchange exchange) throws IOException {
			getThreadNum(exchange, "tomcat");
		}
		
	}
	private static class WeblobicJmxHandler implements HttpHandler {
		
		@Override
		public void handle(HttpExchange exchange) throws IOException {
			getThreadNum(exchange, "weblogic");
		}
		
	}
	
	public static void getThreadNum(HttpExchange exchange,String type) throws IOException{
		String requestMethod = exchange.getRequestMethod();
		if (requestMethod.equals("POST")) {
			Headers responseHeaders = exchange.getResponseHeaders();  
			responseHeaders.set("Content-Type", "text/plain");  
			InputStream in = exchange.getRequestBody();
			StringBuffer out = new StringBuffer(); 
			byte[] b = new byte[4096]; 
			for(int n; (n = in.read(b))!=-1;)   { 
				out.append(new String(b, 0, n)); 
			} 
			String resJson = "";
			try{
				resJson = getThreadNum(out.toString(),type);
				exchange.sendResponseHeaders(200, 0);  
			}catch(Exception e){
				resJson ="";
				exchange.sendResponseHeaders(500, 0);  
			}
			OutputStream responseBody = exchange.getResponseBody();
			responseBody.write(resJson.getBytes());
			responseBody.close();  
		}
	}
	
	@SuppressWarnings("rawtypes")
	public static String getThreadNum(String reqJson,String type) {
		List<Map> resList  = new ArrayList<>();
		if("tomcat".equals(type)){
			resList = TomcatJMXService.getThreadNum(reqJson);
		}else if("weblogic".equals(type)){
			resList = WebLogicJMXService.getThreadNum(reqJson);
		}
		return JSONUtil.obj2json(resList);
	}
}
